<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="巡护任务名称" prop="mission">
        <el-input
          v-model="queryParams.mission"
          placeholder="请输入巡护任务名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务开始时间" prop="taskBeginTime" label-width="100px">
        <el-date-picker clearable size="small"
                        v-model="queryParams.taskBeginTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择任务开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="任务结束时间" prop="taskEndTime" label-width="100px">
        <el-date-picker clearable size="small"
                        v-model="queryParams.taskEndTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择任务结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          @click=""-->
      <!--          v-hasPermi="['frontierCommand:mission:add']"-->
      <!--        >巡护表生成-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          @click=""-->
      <!--          v-hasPermi="['frontierCommand:mission:add']"-->
      <!--        >巡护表复制-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['frontierCommand:mission:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['frontierCommand:mission:edit']"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeleteIds"
          v-hasPermi="['frontierCommand:mission:remove']"
        >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['frontierCommand:mission:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="missionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--<el-table-column label="序号" align="center" prop="id" v-if="true"/>-->
      <el-table-column label="任务名称" align="center" prop="mission"/>
      <el-table-column label="巡护人员" align="center" prop="patrolName"/>
      <el-table-column label="巡护人员账号" align="center" prop="patrolSysName"/>
      <el-table-column label="描述" align="center" prop="descRibe"/>
      <el-table-column label="任务开始时间" align="center" prop="taskBeginTime" width="180">
      </el-table-column>
      <el-table-column label="任务结束时间" align="center" prop="taskEndTime" width="180">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['frontierCommand:mission:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['frontierCommand:mission:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改巡护任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="巡护任务" prop="mission">
              <el-input v-model="form.mission" placeholder="请输入巡护任务"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务开始时间" prop="taskBeginTime">
              <el-date-picker clearable size="small"
                              v-model="form.taskBeginTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择任务开始时间"
                              :picker-options="pickerOptionsStart">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="巡护人员" prop="patrolName">
              <!--<el-row v-if="this.title === '修改巡护任务'">-->
              <el-input v-model="form.patrolName" style="width:120px" disabled="true"/>
              <el-button type="primary" v-model="form.patrolId" @click="selectPatrol"
                         style="margin-left: 10px">请选择巡护人员
              </el-button>
              <!--    </el-row>
                  <el-row v-else>
                    <el-input v-model="form.patrolName" style="width:120px"/>
                    <el-button type="primary" v-model="form.patrolId" @click="selectPatrol" style="margin-left: 10px">
                      请选择巡护人员
                    </el-button>
                  </el-row>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务结束时间" prop="taskEndTime">
              <el-date-picker clearable size="small"
                              v-model="form.taskEndTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择任务结束时间"
                              :picker-options="pickerOptionsEnd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="descRibe">
              <el-input v-model="form.descRibe" type="textarea" placeholder="请输入描述"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="patrolTitle" :visible.sync="patrolOpen" width="800px" append-to-body>
      <el-form :model="queryPatrolParams" ref="queryPatrolForm" :inline="true" v-show="showSearchPatrol"
               label-width="68px" @submit.native.prevent>
        <el-form-item label="登录名" prop="userName">
          <el-input
            v-model="queryPatrolParams.userName"
            placeholder="请输入登录名"
            clearable
            size="small"
            @keyup.enter.native="handleQueryPatrol"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryPatrol">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetPatrolQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="patrolList" @selection-change="handleSelectionChangeTerminal" ref="tb">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="用户id" align="center" prop="userId"/>
        <el-table-column label="登录名" align="center" prop="userName"/>
        <el-table-column label="手机号" align="center" prop="phonenumber"/>
      </el-table>
      <pagination
        v-show="totalPatrol>0"
        :total="totalPatrol"
        :page.sync="queryPatrolParams.pageNum"
        :limit.sync="queryPatrolParams.pageSize"
        @pagination="getPatrolList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="okPatrol">确 定</el-button>
        <el-button @click="cancelPatrol">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import {listAppUser} from "@/api/basicInformation/appUser";
  import {
    listMission,
    getMission,
    delMission,
    addMission,
    updateMission,
    exportMission
  } from '@/api/frontierCommand/mission';

  const validatormission = (rule, value, callback) => {
    const reg = /\d{10,}$/
    if (reg.test(value)) {
      return callback(new Error('输入内容不符合规则'))
    } else {
      callback();
    }
  };

  export default {
    name: 'Mission',
    components: {},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        missionName: '',
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        //搜索巡护人员用到字段
        idsPatrol: [],
        patrolNames: [],
        patrolNumbers: [],
        totalPatrol: 0,
        patrolList: [],
        // 显示搜索条件
        showSearchPatrol: true,
        // 总条数
        total: 0,
        // 巡护任务表格数据
        missionList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 选择人员弹出层标题
        patrolTitle: '选择巡护人员',
        // 是否显示选择人员弹出层
        patrolOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          mission: undefined,
          taskBeginTime: undefined,
          taskEndTime: undefined,
          orderByColumn: 'taskBeginTime',
          isAsc: 'desc'
        },
        // 查询巡护人员                                                                                                                                                                                                                                        参数
        queryPatrolParams: {
          pageNum: 1,
          pageSize: 10,
          userName: undefined,
          userType: 2
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          taskBeginTime: [{
            required: true,
            message: '请选择开始时间',
            validator: this.pickerOptionsStart,
            trigger: 'change'
          }],
          taskEndTime: [{
            required: true,
            message: '请选择结束时间',
            validator: this.pickerOptionsEnd,
            trigger: 'change'
          }],
          /* mission: [
             {
               required: true,
               message: '巡护任务不能为空',
               validator: validatormission,
               trigger: 'change'pattern: /[^\d{5,}]$/,
             }
           ],*/
          mission: [
            {required: true, message: '巡护任务不能为空', trigger: 'blur'},
            {min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur'},
            {required: true, trigger: 'blur', validator: validatormission}
          ],
          descRibe: [
            {required: true, message: '巡护任务不能为空', trigger: 'blur'},
            {min: 0, max: 20, message: '长度在 0 到 200 个字符', trigger: 'blur'}
          ],
          patrolName: [
            {required: true, message: '巡护人员不能为空', trigger: 'change'}
          ]
        },
        pickerOptionsStart: {
          disabledDate: time => {
            let endDateVal = this.form.taskEndTime;
            if (endDateVal) {
              return time.getTime() > new Date(endDateVal).getTime();
            }
          }
        },
        pickerOptionsEnd: {
          disabledDate: time => {
            let beginDateVal = this.form.taskBeginTime;
            if (beginDateVal) {
              return (time.getTime() < new Date(beginDateVal).getTime() - 1 * 24 * 60 * 60 * 1000)
            }
          }
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      /** 查询巡护任务列表 */
      getList() {
        if (new Date(this.queryParams.taskBeginTime).getTime() > new Date(this.queryParams.taskEndTime).getTime()) {
          // this.$notify({
          //   title: `提醒`,
          //   message: `任务开始时间不能大于结束时间`
          // })
          this.$message.error('任务开始时间不能大于结束时间')
        } else {
          this.loading = true
          listMission(this.queryParams).then(response => {
            this.missionList = response.rows
            this.total = response.total
            this.loading = false
          })
        }
      },
      /** 获取巡护人员列表 */
      getPatrolList() {
        this.loading = true;
        listAppUser(this.queryPatrolParams).then(response => {
          this.patrolList = response.rows;
          this.totalPatrol = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          mission: undefined,
          taskBeginTime: undefined,
          taskEndTime: undefined,
          patrolId: undefined,
          patrolName: undefined,
          delFlag: undefined,
          createById: undefined,
          createBy: undefined,
          createTime: undefined,
          updateById: undefined,
          updateBy: undefined,
          updateTime: undefined,
          descRibe: undefined
        }
        this.resetForm('form')
      },
      /** 巡护人员搜索按钮操作 */
      handleQueryPatrol() {
        this.queryPatrolParams.pageNum = 1;
        this.getPatrolList();
      },
      /** 巡护人员重置按钮操作 */
      resetPatrolQuery() {
        this.resetForm("queryPatrolForm");
        this.handleQueryPatrol();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.missionName = ''
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.missionName = selection.map(item => item.mission)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      // 多选框选中数据
      handleSelectionChangeTerminal(selection) {
        this.checkedGh = selection[0].gh;
        if (selection.length > 1) {
          this.$refs.tb.clearSelection();
          this.$refs.tb.toggleRowSelection(selection.pop());
        }
        this.idsPatrol = selection.map(item => item.userId)
        this.patrolNames = selection.map(item => item.userName);
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加巡护任务'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const id = row.id || this.ids
        const t1 = new Date(row.taskBeginTime)
        const t2 = new Date(row.taskEndTime)
        const t3 = Date.now()
        if (t2 < t3 || (t1 < t3 && t2 > t3)) {
          this.msgError('巡护任务已开始，或者已结束，不能修改')
        } else {
          getMission(id).then(response => {
            this.form = response.data
            this.open = true
            this.title = '修改巡护任务'
          })
        }
      },
      /** 选择巡护人员*/
      selectPatrol() {
        this.totalPatrol = 0
        this.patrolList = []
        this.patrolOpen = true
        this.handleQueryPatrol()
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateMission(this.form).then(response => {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
            } else {
              addMission(this.form).then(response => {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id
        this.$confirm('是否确认删除巡护任务名称为"' + row.mission + '"的数据项？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delMission(ids)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
      },
      /** 批量删除按钮操作 */
      handleDeleteIds() {
        const ids = this.ids
        this.$confirm('是否确认删除选中的集合的数据项？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delMission(ids)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        let queryParams1 = { ...this.queryParams }
        queryParams1.pageSize = 99999
        queryParams1.pageNum = 1
        this.$confirm('是否确认导出所有巡护任务数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return exportMission(queryParams1)
        }).then(response => {
          this.download(response.msg)
        })
      },
      okPatrol() {
        if (this.idsPatrol.length > 1) {
          this.msgInfo("只能选择一个巡护人员");
        } else if (this.idsPatrol.length === 1) {
          this.form.patrolId = this.idsPatrol[0];
          this.form.patrolName = this.patrolNames[0];
          this.patrolOpen = false;
        } else {
          this.msgInfo("请选择巡护人员");
        }
      },
      cancelPatrol() {
        this.patrolOpen = false;
      }
    }
  }
</script>
